<template>
  <div class="register-view">
    <h2 class="title">创建账号</h2>
    <p class="subtitle">加入我们，开始AI对话之旅</p>
    
    <form class="register-form" @submit.prevent="handleRegister">
      <div class="form-group">
        <label for="username">用户名</label>
        <div class="input-wrapper">
          <Icon icon="mdi:account-outline" />
          <input 
            id="username"
            v-model="formData.username"
            type="text"
            placeholder="请输入用户名"
            required
            minlength="3"
            maxlength="20"
            @blur="validateUsername"
          />
        </div>
        <p v-if="errors.username" class="error-message">{{ errors.username }}</p>
      </div>

      <div class="form-group">
        <label for="email">邮箱</label>
        <div class="input-wrapper">
          <Icon icon="mdi:email-outline" />
          <input 
            id="email"
            v-model="formData.email"
            type="email"
            placeholder="请输入邮箱地址"
            required
            @blur="validateEmail"
          />
        </div>
        <p v-if="errors.email" class="error-message">{{ errors.email }}</p>
      </div>

      <div class="form-group">
        <label for="phone">手机号码</label>
        <div class="input-wrapper">
          <Icon icon="mdi:phone-outline" />
          <input 
            id="phone"
            v-model="formData.phone"
            type="tel"
            placeholder="请输入手机号码"
            required
            pattern="^1[3-9]\d{9}$"
            @blur="validatePhone"
          />
        </div>
        <p v-if="errors.phone" class="error-message">{{ errors.phone }}</p>
      </div>
      
      <div class="form-group">
        <label for="password">密码</label>
        <div class="input-wrapper">
          <Icon icon="mdi:lock-outline" />
          <input
            id="password"
            v-model="formData.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            required
            minlength="6"
            @blur="validatePassword"
          />
          <Icon 
            class="toggle-password"
            :icon="showPassword ? 'mdi:eye-off' : 'mdi:eye'"
            @click="showPassword = !showPassword"
          />
        </div>
        <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
      </div>

      <div class="form-group">
        <label for="confirmPassword">确认密码</label>
        <div class="input-wrapper">
          <Icon icon="mdi:lock-outline" />
          <input
            id="confirmPassword"
            v-model="confirmPassword"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请再次输入密码"
            required
            @blur="validateConfirmPassword"
          />
          <Icon 
            class="toggle-password"
            :icon="showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'"
            @click="showConfirmPassword = !showConfirmPassword"
          />
        </div>
        <p v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</p>
      </div>


      <button 
        type="submit" 
        class="submit-btn" 
        :disabled="!isFormValid || authStore.loading"
      >
        <span v-if="!authStore.loading">注册</span>
        <Icon v-else icon="eos-icons:loading" class="loading-icon" />
      </button>
    </form>

    <p class="login-link">
      已有账号？
      <router-link to="/auth/login">立即登录</router-link>
    </p>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import type { RegisterRequest } from '@/services/api'
import { message } from '@/services/message'

const router = useRouter()
const authStore = useAuthStore()

const formData = reactive<RegisterRequest>({
  username: '',
  password: '',
  email: '',
  phone: ''
})

const confirmPassword = ref('')
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const errors = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

const validateUsername = () => {
  if (formData.username.length < 3) {
    errors.username = '用户名至少需要3个字符'
  } else if (formData.username.length > 20) {
    errors.username = '用户名不能超过20个字符'
  } else {
    errors.username = ''
  }
}

const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址'
  } else {
    errors.email = ''
  }
}

const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.phone)) {
    errors.phone = '请输入有效的手机号码'
  } else {
    errors.phone = ''
  }
}

const validatePassword = () => {
  if (formData.password.length < 6) {
    errors.password = '密码至少需要6个字符'
  } else {
    errors.password = ''
  }
  validateConfirmPassword()
}

const validateConfirmPassword = () => {
  if (confirmPassword.value !== formData.password) {
    errors.confirmPassword = '两次输入的密码不一致'
  } else {
    errors.confirmPassword = ''
  }
}

const isFormValid = computed(() => {
  return (
    !errors.username &&
    !errors.email &&
    !errors.phone &&
    !errors.password &&
    !errors.confirmPassword &&
    formData.username &&
    formData.email &&
    formData.phone &&
    formData.password &&
    confirmPassword.value
  )
})

const handleRegister = async () => {
  if (!isFormValid.value) {
    message.error('请检查表单填写是否正确')
    return
  }

  try {
    const success = await authStore.register(formData)
    if (success) {
      message.success('注册成功')
      router.push('/chat')
    }
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message)
    } else {
      message.error('注册失败，请稍后重试')
    }
  }
}
</script>

<style lang="scss" scoped>
.register-view {
  .title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 8px;
    text-align: center;
  }

  .subtitle {
    color: #666;
    text-align: center;
    margin-bottom: 32px;
    
    .dark-mode & {
      color: #999;
    }
  }
}

.register-form {
  .form-group {
    margin-bottom: 24px;

    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;

      .iconify {
        position: absolute;
        left: 12px;
        color: #666;
      }

      input {
        width: 100%;
        padding: 12px 12px 12px 40px;
        border: 1px solid #ddd;
        border-radius: 8px;
        font-size: 16px;
        transition: all 0.3s ease;

        &:focus {
          border-color: #42b883;
          box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.2);
        }
      }

      .toggle-password {
        position: absolute;
        right: 12px;
        cursor: pointer;
      }
    }
  }


  .submit-btn {
    width: 100%;
    padding: 12px;
    background: #42b883;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #3aa876;
    }

    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }

    .loading-icon {
      animation: spin 1s linear infinite;
    }
  }
}

.divider {
  text-align: center;
  margin: 24px 0;
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 45%;
    height: 1px;
    background: #ddd;
  }

  &::before {
    left: 0;
  }

  &::after {
    right: 0;
  }

  span {
    background: white;
    padding: 0 12px;
    color: #666;
    
    .dark-mode & {
      background: #2d2d2d;
      color: #999;
    }
  }
}

.social-login {
  .social-btn {
    width: 100%;
    padding: 12px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
    }
  }
}

.login-link {
  text-align: center;
  margin-top: 24px;

  a {
    color: #42b883;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
  min-height: 17px;
}

.form-group {
  margin-bottom: 16px;
}

input:invalid {
  border-color: #ff4d4f;
  
  &:focus {
    box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
  }
}
</style> 